package com.qyhl.cloud.webtv.module_integral.wallet.goldcoin;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qyhl.cloud.webtv.module_integral.R;
import com.qyhl.cloud.webtv.module_integral.R2;
import com.qyhl.cloud.webtv.module_integral.app.IntegralApplication;
import com.qyhl.cloud.webtv.module_integral.common.IntergralUrl;
import com.qyhl.cloud.webtv.module_integral.wallet.WalletActivity;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.intergral.WallerBean;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

public class GlodFragment extends BaseFragment {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.loading_mask)
    LoadingLayout loadingMask;
    @BindView(R2.id.glodform)
    GlodForm glodform;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    /**
     * 最后一条日期
     */
    private String lastdate = "";
    private final String tag = "GlodFragmentTag";
    private List<WallerBean.ExchangeListBean> exchangeList;
    private CommonAdapter<WallerBean.ExchangeListBean> adapter;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.inter_fragment_glod, container, false);
    }

    @Override
    protected void create() {

    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        initView();
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    private void initView() {
        loadingMask.setStatus(LoadingLayout.Loading);
        loadingMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingMask.setStatus(LoadingLayout.Loading);
                //通知activity重新获取数据
                ((WalletActivity) getActivity()).getData();
            }
        });
        exchangeList = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter = new CommonAdapter<WallerBean.ExchangeListBean>(getContext(),
                R.layout.inter_goldcoin_detail_layout, exchangeList) {
            @Override
            protected void convert(ViewHolder viewHolder, WallerBean.ExchangeListBean exchangeListBean, int position) {
                if (getActivity() != null && !getActivity().isFinishing()) {
                    viewHolder.setText(R.id.title, GlodRule.getTitle(exchangeListBean.getType()));
                    viewHolder.setText(R.id.describe, GlodRule.getDescribe(exchangeListBean.getType()));
                    viewHolder.setText(R.id.time, exchangeListBean.getDate());
                    TextView detailed = viewHolder.getView(R.id.detailed);
                    TextView glodText = viewHolder.getView(R.id.glodText);
                    glodText.setText("金币");
                    if (exchangeListBean.getCoin() > 0) {
                        detailed.setText("+" + exchangeListBean.getCoin());
                        detailed.setTextColor(ContextCompat.getColor(getContext(), R.color.global_base));
                        glodText.setTextColor(ContextCompat.getColor(getContext(), R.color.global_base));
                    } else {
                        detailed.setText(String.valueOf(exchangeListBean.getCoin()));
                        detailed.setTextColor(ContextCompat.getColor(getContext(), R.color.global_black_lv0));
                        glodText.setTextColor(ContextCompat.getColor(getContext(), R.color.global_black_lv0));
                    }

                }
            }
        });

        refresh.setEnableLoadMore(true);
        refresh.setEnableRefresh(true);
        //刷新中禁止操作
        refresh.setDisableContentWhenRefresh(true);
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        //下拉刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //通知activity重新获取数据
                ((WalletActivity) getActivity()).getData();
            }
        });

        //加载更多
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getData(lastdate);
            }
        });
    }

    /**
     * 获取更多金币列表数据
     */
    private void getData(String lastdate) {
        if (NetUtil.isNetworkAvalible(IntegralApplication.getApp())) {
            Map<String, String> map = DESedeUtil.encodeMapUrl(IntergralUrl.INTEGRAL_URL);
            JSONObject jsonObject = new JSONObject();
            try {
                String userName = CommonUtils.getInstance().getUserName();
                jsonObject.put("name", "coinHistory");
                jsonObject.put("version", PathConfigConstant.version);
                jsonObject.put("username", userName);
                jsonObject.put("siteId", CommonUtils.getInstance().getSite());
                jsonObject.put("lastDate", lastdate);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            EasyHttp.post(map.get(DESedeUtil.URL))
                    .upBytes(DESedeUtil.encryptMode(map.get(DESedeUtil.CODEKEY),
                            jsonObject.toString()
                    ))
                    .isDecrypt(true)
                    .decryptKet(map.get(DESedeUtil.CODEKEY))
                    .execute(new SimpleCallBack<List<WallerBean.ExchangeListBean>>() {
                        @Override
                        public void onError(ApiException e) {
                            getDataError(TextUtils.isEmpty(e.getMessage()) ? "请求失败" : e.getMessage());
                        }

                        @Override
                        public void onSuccess(List<WallerBean.ExchangeListBean> exchangeListBeans) {
                            getDataSuccess(exchangeListBeans);
                        }
                    });

        } else {
            getDataError("无网络连接，请检查您的网络...");
        }
    }

    private void getDataSuccess(List<WallerBean.ExchangeListBean> beans) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        if (beans == null || beans.isEmpty()) {
            Toasty.normal(getContext(), "没有更多了").show();
        } else {
            exchangeList.addAll(beans);
            adapter.notifyDataSetChanged();
            lastdate = beans.get(beans.size() - 1).getDate();
        }
    }

    private void getDataError(String message) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        Toasty.normal(getContext(), message).show();
    }

    /**
     * activity获取数据后传递过来
     */
    public void setBean(WallerBean data) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadingMask.setStatus(LoadingLayout.Success);

        exchangeList.clear();
        if (data.getExchangeList() != null && !data.getExchangeList().isEmpty()) {
            lastdate = data.getExchangeList().get(data.getExchangeList().size() - 1).getDate();
            exchangeList.addAll(data.getExchangeList());
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }
        List<WallerBean.CoinListBean> coinList = data.getCoinList();
        int[] values = new int[coinList.size()];
        String[] times = new String[coinList.size()];
        for (int i = 0; i < coinList.size(); i++) {
            values[i] = coinList.get(i).getCoin();
            times[i] = coinList.get(i).getDate().substring(5);
        }
        glodform.setValues(values);
        glodform.setTimes(times);
        glodform.update();
    }

    /**
     * activity获取数据失败
     */
    public void dataError(String msg) {
        loadingMask.setErrorText(msg);
        loadingMask.setReloadButtonText("点击重试");
        loadingMask.setErrorImage(R.drawable.error_content);
        loadingMask.setStatus(LoadingLayout.Error);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
